<template>
  <div class="product-details">
    <div class="product-container">

      <imageBar :images="product.imageUrls"></imageBar>
      <!-- 产品信息 -->
      <div class="product-info">
        <h1 class="product-title">{{ product.productName }}</h1>
        <h4 style="margin: 0;letter-spacing: 2px;">{{ product.englishName }}</h4>
        <div class="price-section">
          <span class="current-price">¥{{ product.price }}</span>
          <span v-if="product.originalPrice" class="original-price">¥{{ product.originalPrice }}</span>
        </div>

        <div class="rating-section">
          <p class="top-title">评价</p>
          <el-rate v-model="rating" disabled show-score></el-rate>
          <span class="review-count">({{ reviewCount }}条评价)</span>
        </div>

        <div class="product-specs">
          <span class="spec-value">{{ product.description }}</span>
        </div>

        <div class="count">
          <p class="top-title">数量</p>
          <el-input-number v-model="params.quantity" :min="1" :max="99"
            @change="updateQuantity(params.quantity)"></el-input-number>
        </div>

        <div class="tags">
          <p class="top-title">标签</p>
          <span>{{ product.tags }}</span>
        </div>

        <div class="action-buttons">

          <button class="blackBtn" type="button" @click="addToCart">加入购物车</button>
          
          <button class="redBtn" type="button" @click="buyNow">
            立即购买
          </button>
        </div>
      </div>
    </div>

    <div class="photograph-desc">
      <h1>服务&交付标准</h1>
      <ul>
        <li v-for="descs in desc" :key="descs.id">
          <el-image class="desc-icon" :src="iconImgUrl() + descs.url" alt="" lazy fit="cover" />
          <span style="margin-top: 15px;">{{ descs.title }}</span>
        </li>
      </ul>
    </div>

    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="图文详情" name="图文详情">
        <DetailPage :images="product.detailUrls" />
      </el-tab-pane>
      <el-tab-pane label="评论" name="评论">
        <ReviewList :productId="product.productId" />
      </el-tab-pane>
    </el-tabs>


    <!-- 回顶部按钮 -->
    <el-backtop :right="40" :bottom="40">
      <el-icon>
        <Top />
      </el-icon>
    </el-backtop>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import imageBar from './components/imageBar.vue'
import ReviewList from './components/ReviewList.vue'
import DetailPage from './components/DetailPage.vue'
import { getProductDetail } from '@/apis/prodcut'
import {addCart} from '@/apis/cart'
import {iconImgUrl} from '@/apis/files'

const route = useRoute()
const router = useRouter()

console.log('当前路由参数:', route.query)

const user = ref(JSON.parse(localStorage.getItem("user") || '{}'))
const rating = ref(null)
const reviewCount = ref(null)
const product = ref({})
const params = reactive({
  userId: '',
  productId: '',
  quantity: 1
})
const activeName = '图文详情'
const desc = ref([
  { id: 1, url: 'zaoxing.png', title: '标题一' },
  { id: 2, url: 'fuzhuang.png', title: '标题二' },
  { id: 3, url: 'dipian.png', title: '标题三' },
  { id: 4, url: 'beijing.png', title: '标题四' },
  { id: 5, url: 'dayin.png', title: '标题五' },
])


// 初始化数据
onMounted(() => {
  const productId = route.query.id
   findProductForId(productId)
})

const findProductForId = async (productId) => {
  console.log('获取商品信息，productId:', productId)
  try {
    const res = await getProductDetail(productId)
    if (res.code === '0') {
      product.value = res.data.product
      reviewCount.value = res.data.reviewCount
      rating.value = res.data.averageRating
      // 将 imageUrls 字符串转换为数组
      if (product.value.imageUrls) {
        product.value.imageUrls = product.value.imageUrls.split(',')
      }
      if (product.value.detailUrls) {
        product.value.detailUrls = product.value.detailUrls.split(',')
      }
      if (product.value.scenarios) {
        product.value.scenarios = product.value.scenarios.split(',')
        // 更新 desc 数组的标题
        product.value.scenarios.forEach((scenario, index) => {
          if (index < desc.value.length) {
            desc.value[index].title = scenario
          }
        })
      }
      console.log('获取商品信息成功:', product.value)
    } else {
      console.error('获取商品信息失败:', res.msg)
      ElMessage.error(res.msg)
    }
  } catch (error) {
    console.error('获取商品信息出错:', error)
    ElMessage.error('获取商品信息失败')
  }
}

const addToCart = async () => {
  // 检查用户是否登录
  if (!user.value || !user.value.userInfo || !user.value.userInfo.userId) {
    ElMessage.warning('请先登录后再操作')
    // router.push('/login')
    return
  }
  try {
    params.userId = user.value.userInfo.userId
    params.productId = product.value.productId
    const res = await addCart(params)
    if (res.code === '0') {
      ElMessage.success(res.data)
      router.push('/shopping')
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    console.error('添加购物车失败:', error)
    ElMessage.error('添加购物车失败，请稍后重试')
  }
  console.log(params)
}

const buyNow = () => {
  // 检查用户是否登录
  if (!user.value || !user.value.userInfo || !user.value.userInfo.userId) {
    ElMessage.warning('请先登录后再操作')
    // router.push('/login')
    return
  }
  router.push('/shopping')
}

const updateQuantity = (item) => {
  // 这里可以添加与后端同步的逻辑
  console.log('更新数量:', item)
}
</script>

<style scoped>
.product-details {
  max-width: 850px;
  margin: 20px auto;
  padding: 20px;
}

.product-container {
  display: flex;
  gap: 40px;
  margin-bottom: 50px;
}

.product-images {
  flex: 1;
}

.main-image {
  width: 100%;
  max-width: 500px;
  height: 450px;
  border-radius: 8px;
  object-fit: cover;
}

.thumbnail-container {
  display: flex;
  gap: 10px;
  margin-top: 10px;
}

.thumbnail {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  cursor: pointer;
  border: 2px solid transparent;
}

.thumbnail:hover {
  border-color: #409EFF;
}

.product-info {
  flex: 1;
}

.product-title {
  font-size: 24px;
  margin-bottom: 0px;
}

.price-section {
  margin: 20px 0;
}

.current-price {
  font-size: 28px;
  color: #f56c6c;
  font-weight: bold;
}

.original-price {
  font-size: 18px;
  color: #999;
  text-decoration: line-through;
  margin-left: 10px;
}

.rating-section {
  margin: 20px 0;
  display: flex;
  align-items: center;
}

.review-count {
  margin-left: 10px;
  color: #666;
}

.product-specs {
  margin: 20px 0;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 4px;
}

.spec-item {
  margin: 10px 0;
}

.spec-label {
  color: #666;
}

.spec-value {
  color: #333;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  gap: 15px;
}

.product-description {
  margin-top: 40px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, .1);
}

.photograph-desc {
  width: 750px;
  margin: 0 auto;
}

.photograph-desc ul {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.photograph-desc ul li {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.desc-icon {
  width: 104px;
}

.count {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin: 20px 0;
}

.tags {
  display: flex;
  flex-direction: row;
}

.top-title {
  width: auto;
  margin-right: 15px;
  color: #999;
}

.el-tabs {
  margin: 0 auto;
  margin-top: 20px;
  width: 750px;
  display: flex;
  justify-content: center;
 
  flex-direction: column;
}

:deep(.el-tabs__header) {
  margin-bottom: 0px !important;
  order: 1;
}

:deep(.el-tabs__content) {
  width: 100%;
  order: 2;
}

:deep( .el-tabs__nav-wrap::after) {
  height: 0px;
}

:deep(.el-tabs__item)  {
  font-size: 1.3em;
}

:deep( .el-tabs__item.is-active) {
  color: #000000;
  font-weight: bold;
}

:deep(.el-tabs__active-bar ) {
  background-color: #000000;
}

:deep(.el-tabs__item:hover)  {
  color: #000000;
}
</style>
